package nl.tue.bsdddump;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;

import org.apache.log4j.PropertyConfigurator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import no.catenda.peregrine.model.objects.json.IfdAPISession;
import no.catenda.peregrine.model.objects.json.IfdConcept;
import no.catenda.peregrine.model.objects.json.IfdLanguage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;




public class JerseyTest {
	private static final int MYTHREADS = 30;
	public static void main(String[] args) {
		try {
			
			
			Properties props = new Properties();
			props.load(new FileInputStream("log4j.properties"));
			PropertyConfigurator.configure(props);
			
			
			ClientConfig clientConfig = new DefaultClientConfig();
			clientConfig.getClasses().add(JacksonJsonProvider.class);
			clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
			Client client = Client.create(clientConfig);
			
			MultivaluedMap formData;
			List<NewCookie> cookies = getCookies(client);
			ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
			//response = webResource.accept("application/json").get(ClientResponse.class);
			//		  IfdAPISession session = response.getEntity(IfdAPISession.class);
			//response.

			getLanguages(client, cookies);
			searchTest(client, cookies);
			BufferedWriter out = new BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream("peregrine.out"),"UTF-8"));
/*
			  for(char ch1='a';ch1<='z';ch1++){
				  for(char ch2='a';ch2<='z';ch2++){
					  for(char ch3='a';ch3<='z';ch3++){
						  
						  String search = Character.toString(ch1)+
								  		Character.toString(ch2)+
								  		Character.toString(ch3);
				          System.out.println("searching "+search);   
						  String result = searchString(client, cookies, search);
				             if (result.equalsIgnoreCase("null") == false){
				            	 out.write("searchResult["+search+"]:"+result+"\n");
				            	 out.flush();
				            	 System.out.println("searchResult["+search+"]:"+result);
				             }
				             
				          Runnable worker = new PeregrineSearchWorker(search,cookies);
				            executor.execute(worker);
				       }    
			       }    
		       }*/
			  
			 
			 out.close();
			 executor.shutdown();
		        // Wait until all threads are finish
		        while (!executor.isTerminated()) {
		 
		        }
			
//IfdLanguage[] ifdLanguages =  langR.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(IfdLanguage[].class);;
//  IfdLanguage[] ifdLanguages =  langR.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(IfdLanguage[].class);;
//List<IfdLanguage> myObjects = mapper.readValue(res, mapper.getTypeFactory().constructCollectionType(List.class, IfdLanguage.class));	
//	  List<IfdLanguage> ifdLanguages =  langR.accept(MediaType.APPLICATION_JSON).cookie(cookies.get(0)).get(new GenericType<List<IfdLanguage>>(){});;
			//	 
		  //	 IfdLanguage[] ifdLanguages = langR.
		// IfdLanguage[] lang = langR.get(IfdLanguage[].class);
		  
		  WebResource concept = client
				  
				   .resource("http://bsddpilot.catenda.no/api/4.0/IfdConcept/search/door");
		  //langR=.cookie(cookies.get(0));
		   formData = new com.sun.jersey.core.util.MultivaluedMapImpl();
			formData.add("searchString", "door");
			//formData.add("password", "demo");
//			
//		  IfdConcept[] ifdConcept=  concept.accept(MediaType.APPLICATION_JSON)
//				  .type(MediaType.APPLICATION_FORM_URLENCODED)
//				  .cookie(cookies.get(0))
//				  .get(IfdConcept[].class);;
//	
		  
		  
//		if (response.getStatus() != 200) {
//		   throw new RuntimeException("Failed : HTTP error code : "
//			+ response.getStatus());
//		}
// 
//		String output = response.getEntity(String.class);
// 
//		System.out.println("Output from Server .... \n");
//		System.out.println(output);
// 
	  } catch (Exception e) {
 
		e.printStackTrace();
 
	  }
 
	}

	private static List<NewCookie> getCookies(Client client) {
		WebResource webResource = client
				.resource("http://bsddpilot.catenda.no/api/4.0/session/login?email=demo&password=demo");
		MultivaluedMap formData = new com.sun.jersey.core.util.MultivaluedMapImpl();
		formData.add("email", "demo");
		formData.add("password", "demo");



		webResource.accept(MediaType.APPLICATION_JSON_TYPE);
		webResource.type(MediaType.APPLICATION_FORM_URLENCODED);

		ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class,formData);
		System.out.println(response.getStatus());
		List<NewCookie> cookies = response.getCookies();
		if (cookies != null && cookies.size() > 0) {
			for (NewCookie c : cookies) {
				System.out.println(c+"    ");
			}
		}
		return cookies;
	}

	private static void getLanguages(Client client, List<NewCookie> cookies) throws IOException, JsonProcessingException, JsonParseException, JsonMappingException {
		WebResource langR = client

				.resource("http://bsddpilot.catenda.no/api/4.0/IfdLanguage");
		//langR=.cookie(cookies.get(0));
		String res =  langR.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(String.class);;
		System.out.println(res);
		ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

		mapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		//mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		res=res.replace("\"IfdLanguage\":", "");
		res=res.replace("{[{", "[{");
		res=res.replace("}]}", "}]");
		System.out.println(res);
		JsonNode jsonNode = mapper.readTree(res);
		System.out.println(jsonNode.isArray());
		IfdLanguage[] langs = mapper.readValue(res,IfdLanguage[].class);
		System.out.println(langs.toString());
	}

private static void searchTest(Client client, List<NewCookie> cookies) throws IOException, JsonProcessingException, JsonParseException, JsonMappingException {
	String s= URLEncoder.encode("*","UTF-8");
	WebResource langR = client
	
	.resource("http://bsddpilot.catenda.no/api/4.0/IfdConcept/search/"+"doo"+s);
	//langR=.cookie(cookies.get(0));
	String res =  langR.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(String.class);;
	try {
		Map jsonJavaRootObject = new Gson().fromJson(res,Map.class);
		JsonElement jelement = new JsonParser().parse(res);
	    JsonObject  jobject = jelement.getAsJsonObject();
//	    jobject = jobject.getAsJsonObject("IfdConcept");
	    JsonArray jarray = jobject.getAsJsonArray("IfdConcept");
	    Gson gson = new GsonBuilder().create();
        IfdConcept c = gson.fromJson(jarray.get(0).toString(),IfdConcept.class);	
        
        ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
    	//String s= URLEncoder.encode("*","UTF-8");
    	mapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    	mapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    	//mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    	JsonNode root = mapper.readTree(res);
    	JsonNode concepts = root.get("IfdConcept");
    	
    	
    	
        Iterator<JsonNode> iterator = concepts.iterator();
    	while (iterator.hasNext()) {
			JsonNode jsonNode = (JsonNode) iterator.next();
			IfdConcept langs = mapper.readValue(jsonNode,IfdConcept.class);
			System.out.println(langs.toString());
		}
	    jobject = jarray.get(0).getAsJsonObject();
	    String result = jobject.get("translatedText").toString();
		
		JSONObject jsonObject = (JSONObject) ((Object)res);
		JSONArray msg = (JSONArray) jsonObject.get("IfdConcdept");
		for (int i = 0; i < msg.length(); i++) {  // **line 2**
		     JSONObject childJSONObject = msg.getJSONObject(i);
		     String name = childJSONObject.getString("name");
		     int age     = childJSONObject.getInt("age");
		}
	
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	System.out.println(res);
	ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
	//String s= URLEncoder.encode("*","UTF-8");
	mapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	//mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	res=res.replace("\"IfdConcept\":", "");
	res=res.replace("{[{", "[{");
	res=res.replace("}]}", "}]");
	System.out.println(res);
	JsonNode jsonNode = mapper.readTree(res);
	System.out.println(jsonNode.isArray());
	IfdConcept[] langs = mapper.readValue(res,IfdConcept[].class);
	System.out.println(langs.toString());
}




private static String searchString(Client client, List<NewCookie> cookies, String searchTerm) throws IOException, JsonProcessingException, JsonParseException, JsonMappingException {
	String s= URLEncoder.encode("*","UTF-8");
	WebResource langR = client
	
	.resource("http://bsddpilot.catenda.no/api/4.0/IfdConcept/search/"+searchTerm+s);
	//langR=.cookie(cookies.get(0));
	String res =  langR.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(String.class);;
	return res;
}
}


